package com.user.controller;

import com.user.utils.R;
import io.lettuce.core.dynamic.annotation.Param;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author : Yu
 * @Date 2023/12/29 15:25
 */
@RestController
@RequestMapping("/ftp")
@Log4j2
public class FtpController {

    private final String FOLDER = "D:/Desktop/毕业设计/cache/";

    @PostMapping(value = "/upload")
    public R uploadServer(@RequestParam("path") String path, @RequestParam("file") MultipartFile file) {
        // 上传文件保存到本地
        try {
            // 创建目标文件对象
            File destFile = new File(FOLDER + path + File.separator + file.getOriginalFilename());
            // 如果目标文件的父目录不存在，则创建
            if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
            // 将上传的文件保存到目标文件中
            file.transferTo(destFile);
            return R.ok("文件上传成功");
        } catch (IOException e) {
            FtpController.log.error(e.getMessage());
            return R.error("文件上载失败");
        }
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@Param("path") String path, @Param("fileName") String fileName) {
        Path filePath = Paths.get(FOLDER + path, fileName);
        if (!Files.exists(filePath)) return ResponseEntity.status(HttpStatus.NOT_FOUND).body("找不到文件".getBytes());
        byte[] fileBytes;
        try {
            fileBytes = Files.readAllBytes(filePath);
        } catch (IOException e) {
            FtpController.log.error(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("读取文件时出错".getBytes());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        return ResponseEntity.ok().headers(headers).body(fileBytes);
    }


    @GetMapping("/delete")
    public R delete(@Param("path") String path, @Param("fileName") String fileName) {
        Path filePath = Paths.get(FOLDER + path, fileName);
        if (!Files.exists(filePath)) return R.error("找不到文件");
        try {
            Files.delete(filePath);
            return R.ok("文件删除成功");
        } catch (IOException e) {
            FtpController.log.error(e.getMessage());
            return R.error("文件删除失败");
        }
    }
}
